package com.yimixian.app.ui;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yimixian.app.R;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.common.Constants;
import com.yimixian.app.model.HeadInfo;

import java.util.ArrayList;
import java.util.List;

public class ScrollPlayView extends RelativeLayout {

    private Context context;
    private List<View> dataList = new ArrayList<>();
    private int duration = 500; //动画滚动时间
    private int interval = 3000; //动画结束后间隔时间
    private TranslateAnimation transCur, transNext;
    private View vCur, vNext;
    private ScrollDirection direction = ScrollDirection.FROM_DOWN_TO_TOP;
    private int curIndex = 0;
    private HomeHeadView.OnHeadViewClickListener mHeadViewClickListener;
    private LinearLayout ll_main;
    private RelativeLayout rl_right;
    private float density;
    private PlayThread playThread;
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {

            boolean flag = false;
            FragmentManager fragmentManager =  ((YMXMainActivity) getContext()).getSupportFragmentManager();
            List<Fragment> fragments = fragmentManager.getFragments();
            for(Fragment fragment : fragments){
                if(fragment != null && fragment.isVisible() && "HomeFragment".equals(fragment.getClass().getSimpleName())){

                    if (dataList.size() > 0) {
                        flag = true;
                        if(curIndex == dataList.size()){
                            curIndex = 0;
                        }
                        int nextIndex = curIndex + 1 == dataList.size() ? 0 : curIndex + 1;
                        vCur = dataList.get(curIndex);
                        vNext = dataList.get(nextIndex);
                        vCur.startAnimation(transCur);
                        vNext.startAnimation(transNext);
                        curIndex++;
                    }

                    break;
                }
            }
            if(!flag){
                transCur.cancel();
                transNext.cancel();
            }
        }
    };

    public enum ScrollDirection{
        FROM_DOWN_TO_TOP,
        FROM_TOP_TO_DOWN;
    }


    public ScrollPlayView(Context context) {
        super(context);
        intiView();
    }

    public ScrollPlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        intiView();
    }

    public ScrollPlayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        intiView();
    }

    private void intiView(){
        setBackgroundColor(Color.WHITE);
        density = getContext().getResources().getDisplayMetrics().density;
        setPadding((int) (density * 17), 0, (int) (density * 17), 0);
        View view = new View(getContext());
        view.setId(R.id.v_margin);
        view.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int) (1 * density)));
        view.setBackgroundColor(Color.rgb(238, 238, 238));
        addView(view);
        ll_main = new LinearLayout(getContext());
        ll_main.setOrientation(LinearLayout.HORIZONTAL);
        ll_main.setGravity(Gravity.CENTER);
        rl_right = new RelativeLayout(getContext());
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.BELOW, R.id.v_margin);
        addView(ll_main, lp);
        ImageView iv = new ImageView(getContext());
        iv.setImageResource(R.drawable.yimikuaibao);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);
        ll_main.addView(iv);
        View viewLine = new View(getContext());
        viewLine.setBackgroundColor(Color.rgb(238, 238, 238));
        LinearLayout.LayoutParams lp_ = new LinearLayout.LayoutParams((int) (1 * density), LayoutParams.MATCH_PARENT);
        lp_.setMargins((int) (10 * density), (int) (5 * density), (int) (12 * density), (int) (5 * density));
        ll_main.addView(viewLine, lp_);

        if(direction == ScrollDirection.FROM_DOWN_TO_TOP){
            transCur = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f);
            transNext = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f);
        }else if(direction == ScrollDirection.FROM_TOP_TO_DOWN){
            transCur = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f);
            transNext = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f);
        }
        transCur.setDuration(duration);
        transNext.setDuration(duration);
        transCur.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                vCur.setVisibility(View.VISIBLE);
                vNext.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                vCur.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

    }

    public void play(final int delay){
        //只有一条不轮播
        if(rl_right.getChildCount() <= 1)
            return;
        try {
            if(playThread != null)
                playThread.isStop = true;
            playThread = new PlayThread(delay);
            playThread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void bind(List<HeadInfo> mList, final HomeHeadView.OnHeadViewClickListener
            mHeadViewClickListener){
        if (mList == null) return;
        this.mHeadViewClickListener = mHeadViewClickListener;
        int height = (int) (getContext().getResources().getDisplayMetrics().density * 36);
        dataList.clear();
        curIndex = 0;
        transCur.cancel();
        transNext.cancel();
        rl_right.removeAllViews();
        for (int i = 0; i < mList.size(); i++){
            HeadInfo headInfo = mList.get(i);
            LinearLayout ll_row = new LinearLayout(getContext());
            ll_row.setGravity(Gravity.CENTER_VERTICAL);
            ll_row.setOrientation(LinearLayout.HORIZONTAL);
            ll_row.setBackgroundColor(Color.WHITE);
            ll_row.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, height));
            TextView tvHead = new TextView(getContext());
            tvHead.setGravity(Gravity.CENTER);
            String title = headInfo.title == null ? "" : headInfo.title;
            if(title.length() > 2){
                title = title.substring(0, 2);
            }
            tvHead.setText(title);
            tvHead.setTextColor(getContext().getResources().getColor(R.color.ymx_orange));
            tvHead.setTextSize(12);
            float width = tvHead.getPaint().measureText("俩字");
            tvHead.setBackgroundResource(R.drawable.order_list_complain_bg_normal);
            tvHead.setPadding((int) (density * 3), (int) (density * 1), (int) (density * 3), (int) (density * 1));
            width += density * 3 * 2;
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams((int) width, LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, 0, (int) (density * 5), 0);
            ll_row.addView(tvHead, lp);
            TextView tvDescription = new TextView(getContext());
            tvDescription.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            tvDescription.setText(headInfo.desc);
            tvDescription.setTextColor(Color.rgb(33, 33, 33));
            tvDescription.setTextSize(12);
            tvDescription.setSingleLine(true);
            tvDescription.setEllipsize(TextUtils.TruncateAt.END);
            ll_row.addView(tvDescription);
            if(i == 0)
                ll_row.setVisibility(View.VISIBLE);
            else
                ll_row.setVisibility(View.INVISIBLE);
            ll_row.setTag(i);
            ll_row.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mHeadViewClickListener != null) mHeadViewClickListener.OnHeadViewClick(
                            Constants.HeadViewType.SetHeadLine, (int) view.getTag());
                }
            });
            dataList.add(ll_row);
            rl_right.addView(ll_row);
        }
        ll_main.addView(rl_right, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    }

    private boolean isPause = false;

    public void setIsPause(boolean isPause) {
        this.isPause = isPause;
    }

    class PlayThread extends Thread{

        public boolean isStop = false;
        private int delay;

        public PlayThread(int delay) {
            this.delay = delay;
        }

        @Override
        public void run() {

            try {
                sleep(delay <= 0 ? 0 : delay);
                while(!isStop){
                    if(!isPause){
                        handler.sendEmptyMessage(0);
                    }
                    sleep(duration + interval);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
